package com.frontop.terminal.gangedsocket.core;


import cn.hutool.core.thread.ThreadUtil;
import com.frontop.terminal.gangedsocket.config.PlayGangedConfig;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * <p>
 * 播放联动Socket服务端
 * </P>
 *
 * @author Guodong
 */

public class PlayGangedServiceSocket implements Runnable {

    public static final String COLSE = "COLSE";
    static List<PlayGangedService> clients = new ArrayList<>(16);
    private static boolean release = true;
    private static ServerSocket serverSocket;

    public static void release() {
        release = false;

        //向所有客户端发送关闭命令
        sendToAllSocket(COLSE);

        //释放所有连接
        for (PlayGangedService socket : clients) {
            socket.release();

            if (clients.isEmpty()) {
                break;
            }
        }

        try {
            if (Objects.nonNull(serverSocket)) {
                serverSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        Heartbeat.release();
    }

    public static void start() {
        release = true;
        PlayGangedServiceSocket playGangedServiceSocket = new PlayGangedServiceSocket();
        ThreadUtil.execAsync(playGangedServiceSocket);
    }

    public static void sendToAllSocket(String msg) {
        if (PlayGangedServiceSocket.clients.isEmpty()) {
            System.out.println("[播放联动socket服务端]取消发送信息,原因客户端列表为空");
            return;
        }

        System.out.println("[播放联动socket服务端]收到发送命令,即将发送内容:" + msg);

        for (PlayGangedService socket :
                PlayGangedServiceSocket.clients) {
            socket.send(msg);
        }
    }

    @Override
    public void run() {
        try {
            System.out.println("[播放联动socket服务端]本机通讯地址:" + PlayGangedConfig.HOST_ADDRESS);
            serverSocket = new ServerSocket(PlayGangedConfig.PORT, PlayGangedConfig.CONNECTION_MAX);

            while (release) {
                //这里会等待有连接才往下运行
                Socket socket = serverSocket.accept();

                if (release) {
                    PlayGangedService playGangedService = new PlayGangedService(socket);
                    ThreadUtil.execAsync(playGangedService);
                    clients.add(playGangedService);
                    System.out.println("[播放联动socket服务端]有新的连接建立通讯,当前连接数: " + clients.size());
                }

            }

        } catch (SocketException e) {
            System.out.println("[播放联动socket服务端]通道关闭");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

